#!/usr/bin/bash
vm_temp_name=$1
new_vm_name=$2
new_vm_path=$3
new_vm_path=${new_vm_path:-'/vms/data/disks'}
count_block_num=$(virsh domblklist $1  |egrep 'qcow2|raw'|wc -l)
str0=$2
str1=${str0: -4}

function check()
{
if [ $? == 0 ]
then
echo -e "\033[32m${1}==============================>success\033[0m"  
else
echo -e "\033[31m${1}==============================>fail\033[0m"  
fi
}

function get_new_path()
{
for disk_num in $(seq 1 $count_block_num);
do
	echo " -f ${new_vm_path}/${new_vm_name}-${disk_num}.qcow2" >>/tmp/vm_clone.txt
done
}

function clone_new_vm()
{
block_dest_name=$(cat /tmp/vm_clone.txt)
virt-clone -o $vm_temp_name --auto-clone -n $new_vm_name $block_dest_name
}

function add_disk_serial()
{
block_name=$(virsh domblklist  $new_vm_name |egrep 'qcow2|raw' |awk '{print $1}')
for bolck in ${block_name};do
     random=${RANDOM}${str1^^}
     sed -i "/$bolck/a\\ \ \ \ \ \ <serial>${random}</serial>" /etc/libvirt/qemu/${new_vm_name}.xml
done
}

if [ -z "$4" ]; then
	get_new_path; 
	clone_new_vm;
	add_disk_serial;
        virsh define /etc/libvirt/qemu/${new_vm_name}.xml;
        rm -rf /tmp/vm_clone.txt;
else
	echo "请以些格式输入: vm-clone [vm-template-name] [new-vm-name] [path]"
fi
